﻿#define DEBUG_AGENT

using Microsoft.Phone.Scheduler;
using SmarterCharger.Library.Services.Interfaces;
using System;
using System.Diagnostics;
using System.Windows;

namespace SmarterCharger.BackgroundAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        static ScheduledAgent()
        {
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
                Debugger.Break();
        }

        protected override async void OnInvoke(ScheduledTask task)
        {
            try
            {
                Bootstrapper.Run();

                var smartChargeStopper = ContainerInitializer.Get<ISmartChargeStopper>();
                var isStopped = await smartChargeStopper.Stop();

                if (isStopped)
                    Unschedule(task);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (Debugger.IsAttached)
                    Debugger.Break();
            }

#if DEBUG_AGENT
  ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif

            NotifyComplete();
        }

        private static void Unschedule(ScheduledTask task)
        {
            task.ExpirationTime = DateTime.Now.AddMinutes(1);
        }
    }
}